import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const defaultState = {
  oauth: {
    userId: null,
    authorization: null,
    expires: 0,
    refreshToken: null
  },
  user: {
    id: null,
    name: null,
    account: null,
    roles: null
  },
  activeMenu: 0,
  workbenchCrumbs: [{
    icon: 'md-home',
    label: '首页',
    path: '/home',
    activedMenu: 0
  }]
};

const defaultMutations = {
  setAccessToken (state, token) {
    state.oauth.authorization = `${token.token_type} ${token.access_token}`;
    state.oauth.expires = token.expires_in;
    state.oauth.refreshToken = token.refresh_token;

    let current = new Date();
    current.setSeconds(current.getSeconds() + token.expires_in);

    sessionStorage.setItem('oauth', JSON.stringify(token));
    sessionStorage.setItem("sid-expires", current.getTime());
  },
  logOn (state, user) {
    state.user.id = user.Id;
    state.user.name = user.Name;
    state.user.account = user.Account;
    state.user.roles = user.Roles;

    state.oauth.userId = user.Id;

    sessionStorage.setItem("sid", user.Id);
  },
  logOff (state) {
    state.user.id = null;
    state.user.name = null;
    state.user.account = null;
    state.user.roles = null;

    state.oauth.userId = null;
    state.oauth.authorization = null;
    state.oauth.expires = 0;
    state.oauth.refreshToken = null;

    sessionStorage.removeItem('sid');
    sessionStorage.removeItem('oauth');
    sessionStorage.removeItem('sid-expires');
  },
  changeMenu (state, menu) {
    state.activeMenu = menu;
  },
  workbenchCrumbs (state, crumbs) {
    if (crumbs) {
      state.workbenchCrumbs.splice(1, state.workbenchCrumbs.length, ...crumbs);
    } else {
      state.workbenchCrumbs.splice(1, state.workbenchCrumbs.length);
    }
  }
};

const defaultGetters = {
  /**
   * 判断是否登录
   * @param {Object} state 
   */
  isLogged (state) {
    return () => isLoggedFunc();
  },
  menus (state) {
    return () => {
      if (isLoggedFunc()) {
        return state.menus.filter(m => !m.meta || m.meta.requireAuth || !m.meta.hideInLogged);
      }

      return state.menus.filter(m => m.visible != false && (!m.meta || !m.meta.requireAuth));
    }
  }
};

let isLoggedFunc = () => {
  let sid = sessionStorage.getItem('sid');
  let oauth = sessionStorage.getItem('oauth');

  if (!sid || !oauth) {
    return false;
  }

  let expiresIn = parseInt(sessionStorage.getItem('sid-expires') || 0);

  if (!expiresIn) {
    return false;
  }

  let currentTime = new Date().getTime();

  if (expiresIn < currentTime) {
    return false;
  }

  return true;
};

export default {
  init (state, mutations, getters) {
    let mergedState = Object.assign({}, state, defaultState);
    let mergedMutations = Object.assign({}, mutations, defaultMutations);
    let mergedGetters = Object.assign({}, getters, defaultGetters);

    return new Vuex.Store({
      state: mergedState,
      mutations: mergedMutations,
      getters: mergedGetters
    });
  }
};
